
from common.NeqReq import NeqReq


url = "http://api.airplane.com/check"

airports = ['BJ','TJ','SH','NJ','XA','WH','ZZ','CS','XM','GZ','SZ']
times = [1,2,3]

nr = NeqReq()

lowest_price = -1
lowest_path = []
lowest_times = []

price = 0
path1 = []
path2 = []

def main():
	# 1
	for t in times:
		for airport in airports:
			p = check('SZ',airport,t)
			if p > 0 :
				path1.append({
					'to':airport,
					'price':p,
					'time':t
				})

	for path in path1:
		if path['to'] == 'BJ':
			set(path['price'], [path['time']], ['SZ','BJ'])
		elif path['time'] == 2:
			p = check(path['to'],'BJ',3)
			if p != -1:
				set(path['price']+p,[2,3],['SZ',path['to'],'BJ'])
		elif path['time'] == 1:
			path['next'] = []
			for t in [2,3]:
				for airport in airports:
					if airport == 'SZ': continue
					p = check(path['to'],airport,t)
					if p > 0 :
						path['next'].append({
							'to':airport,
							'price':p,
							'time':t
						})
						path2.append(path)

	for path in path2:
		for pa in path['next']:
			if pa['to'] == 'BJ':
				set(path['price']+pa['price'], [path['time'],pa['time']], ['SZ',path['to'],'BJ'])
			elif pa['time'] == 2:
				p = check(pa['to'],'BJ',3)
				if p != -1:
					set(path['price']+pa['path']+p,[1,2,3],['SZ',path['to'],pa['to'],'BJ'])

	if lowest_price != -1:
		print(f"最低价格为{lowest_price},路径为{lowest_path},航班时间分别为{lowest_times}")


def set(price, times, path):
	if price < lowest_price or lowest_price == -1:
		lowest_price = price
		lowest_times = times
		lowest_path = path
	
#time: 1, 2, 3
def check(start, end, time):
	
	result = nr.send_request('POST', url, {
		'start': start,
		'end': end,
		'time': time
	})

	if result['code'] != 200:
		return -1

	body = result['body']

	if body['available'] != 1:
		return -1

	return body['price']
	



